package cc.uncarbon.module.appapi.web;


import cc.uncarbon.framework.core.context.TenantContext;
import cc.uncarbon.framework.core.context.UserContext;
import cc.uncarbon.framework.web.model.response.ApiResult;
import cc.uncarbon.module.appapi.constant.AppApiConstant;
import cc.uncarbon.module.appapi.model.request.UserLoginDTO;
import cc.uncarbon.module.appapi.model.vo.UserLoginVO;
import cc.uncarbon.module.appapi.service.UserService;
import cc.uncarbon.module.appapi.util.StpUserUtil;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Dict;
import com.yanrumiao.entity.UserEntity;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;


@Tag(name = "小程序商城鉴权接口")
@RequestMapping(AppApiConstant.HTTP_API_URL_PREFIX + "/api/v1")
@RequiredArgsConstructor
@RestController
@Slf4j
public class AppAuthController {

    private final UserService userService;

    @Operation(summary = "登录")
    @PostMapping("/auth/login")
    public ApiResult<UserLoginVO> login(@RequestBody @Valid UserLoginDTO dto) {
        // 可参考 admin-api 的 AdminAuthController#login
        UserEntity user = userService.login(dto);
        // 构造用户上下文
        UserContext userContext = UserContext.builder()
                .userId(user.getId())
                .userName(user.getName())
                .userPhoneNo(user.getPhone())
                .userTypeStr("APP_USER")
                .extraData(null)
                .build();
        TenantContext tenantContext = TenantContext.builder()
                .tenantId(user.getTenantId())
                .build();
        StpUtil.login(user.getId());
        UserLoginVO loginVO = new UserLoginVO();
        loginVO.setUserInfo(user);
        loginVO.setTokenValue(StpUtil.getTokenValue());
        StpUtil.getSession().set(UserContext.CAMEL_NAME, userContext);
        StpUtil.getSession().set(TenantContext.CAMEL_NAME, tenantContext);
        return ApiResult.data("登录成功", loginVO);
    }

    @Operation(summary = "微信登录")
    @GetMapping("/auth/loginwx/{code}")
    public ApiResult<UserLoginVO> loginwx(@PathVariable String code) {

        UserEntity user = userService.loginwx(code);
        // 构造用户上下文
        UserContext userContext = UserContext.builder()
                .userId(user.getId())
                .userName(user.getName())
                .userPhoneNo(user.getPhone())
                .userTypeStr("APP_USER")
                .extraData(new Dict().set("openId", user.getWxOpenId())

                )
                .build();

        StpUtil.login(user.getId());
        StpUtil.getSession().set(UserContext.CAMEL_NAME, userContext);
        TenantContext tenantContext = new TenantContext();
        tenantContext.setTenantId(user.getTenantId());
        StpUtil.getSession().set(TenantContext.CAMEL_NAME, tenantContext);
        UserLoginVO loginVO = new UserLoginVO();
        loginVO.setUserInfo(user);
        String tokenValue = StpUtil.getTokenValue();
        loginVO.setTokenValue(tokenValue);
        // 添加日志，确认 token 是否正确生成
        log.debug("[AppAuthController] 生成的 token 值 >> {}", tokenValue);
        return ApiResult.data("登录成功", loginVO);
    }

}
